#!/bin/bash

if [[ -z $1 ]]; then
  TARGET="./new.cc"
else
  TARGET="$1"
fi

EXT="`echo $TARGET | sed 's/.*\.//'`" # regexes are greedy, so sed (unlike cut)
				#  works even if the filename contains .

if [[ -f "$TARGET" ]]; then
	echo "File $TARGET already exists. Overwrite [y/N]?"
	read OVERWRITE
	if [[ "$OVERWRITE" != "y" ]]; then
		echo "Aborting."
		exit 1
	fi
fi

if [[ -f "./.template.$EXT" ]]; then
	cp "./.template.$EXT" "$TARGET" && open.sh "$TARGET"
else
	if [[ -f "$HOME/.Templates/$TARGET" ]]; then # works only if in target's
					# dir; TODO
		cp "$HOME/.Templates/$TARGET" "$TARGET" && open.sh "$TARGET"
	else
		cp "$HOME/.Templates/template.$EXT" "$TARGET" && open.sh "$TARGET"
	fi
fi

exit $?
